const Koa = require("koa");
const fs = require('fs')
const path = require('path')

const app = new Koa();
app.use((ctx) => {
  const url = ctx.request.url
  console.log(url)

  if(url === '/'){
    // 加载html
    ctx.body = fs.readFileSync('./index.html', 'utf-8')

  }else if(url.endsWith('.js')){
    // 找到对应的路径 去加载 然后返回给浏览器
    const p = path.resolve(__dirname, url.slice(1))
    ctx.type = "text/javascript"
    

    // 做一个标识  如果是 import * from 'vue' => node_modules
    // tag ===  /@modules
    const source = fs.readFileSync(p, "utf-8")
    // 重写
    ctx.body = rewriteImport(source)

  }else if(url.startsWith("/@modules")){
    // 应该去 node_modules 中查找
    const moduleName = url.replace("/@modules/", "")
    // url => vue
    const prefix = path.resolve(__dirname, "node_modules", moduleName)
    // package.json
    const module = require(prefix + "/package.json").module

    ctx.body = fs.readFileSync(path.resolve(prefix, module), "utf-8")
  }
})

function rewriteImport(source) {
  // 匹配 import * from 'vue'
  const reg = /(from\s+['|"])(?![\.\/])/g
  return source.replace(reg, "$1/@modules/")
               .replace(/procee\.env\.NODE_ENV/g, '"development"')
}

app.listen(8000, (ctx) => {
  console.log("open server localhost:8000");
});
